package com.conf4j.svn.kit;

import java.io.File;

import org.tmatesoft.svn.core.SVNDepth;
import org.tmatesoft.svn.core.SVNException;
import org.tmatesoft.svn.core.SVNURL;
import org.tmatesoft.svn.core.internal.io.dav.DAVRepositoryFactory;
import org.tmatesoft.svn.core.internal.io.fs.FSRepositoryFactory;
import org.tmatesoft.svn.core.internal.io.svn.SVNRepositoryFactoryImpl;
import org.tmatesoft.svn.core.wc.SVNClientManager;
import org.tmatesoft.svn.core.wc.SVNRevision;
import org.tmatesoft.svn.core.wc.SVNUpdateClient;
import org.tmatesoft.svn.core.wc.SVNWCUtil;

/**
 * Svn工具类
 * 
 * @author dingnate
 *
 */
public class SvnKit {
	static {
		SVNRepositoryFactoryImpl.setup();
		DAVRepositoryFactory.setup();
		FSRepositoryFactory.setup();
	}

	SvnKit() {
	}

	public static void doCheckoutOrUpdate(File localPath, String svnuri, String user, String password,
			SVNRevision revision) throws SVNException {
		if (new File(localPath, ".svn").exists())
			doUpdate(localPath, user, password, revision);
		else
			doCheckout(localPath, svnuri, user, password, revision);
	}

	/**
	 * 获取SVNClientManager实例
	 * 
	 * @param svnuser
	 * @param svnpasswd
	 * @return
	 */
	private static SVNClientManager getSVNManager(String svnuser, String svnpasswd) {
		SVNClientManager manager = SVNClientManager.newInstance(SVNWCUtil.createDefaultOptions(true), svnuser,
				svnpasswd);
		return manager;
	}

	public static void doUpdate(File checkoutPath, String svnuser, String svnpasswd, SVNRevision revision)
			throws SVNException {
		if (revision == null)
			revision = SVNRevision.HEAD;
		SVNClientManager manager = null;
		try {
			manager = getSVNManager(svnuser, svnpasswd);
			SVNUpdateClient updateClient = manager.getUpdateClient();
			updateClient.doUpdate(checkoutPath, revision, SVNDepth.INFINITY, false, false);
		} finally {
			if (manager != null)
				manager.dispose();
		}
	}

	public static void doCheckout(File checkoutPath, String svnuri, String svnuser, String svnpasswd,
			SVNRevision revision) throws SVNException {
		if (revision == null)
			revision = SVNRevision.HEAD;
		SVNClientManager manager = null;
		try {
			manager = getSVNManager(svnuser, svnpasswd);
			SVNUpdateClient updateClient = manager.getUpdateClient();
			updateClient.doCheckout(SVNURL.parseURIEncoded(svnuri), checkoutPath, revision, revision,
					SVNDepth.INFINITY, false);
		} finally {
			if (manager != null)
				manager.dispose();
		}
	}
}
